#include <iostream>
#include <unistd.h>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "Comm.hpp"
#include "Log.hpp"
#include "InetAddr.hpp"

void Usage(std::string proc)
{
    std::cerr << "Usage: " << proc << "ServerIp ServerPort" << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    Console();
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    // 创建套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        LOG(LogLevel::ERROR) << "create sockfd error";
        exit(SOCKET_CREATE_ERR);
    }

    // 客户端不需要显示bind, 系统会自动bind
    // 客户端也不需要listen和accept

    // 客户端需要向服务端发送连接请求
    // 系统进行bind发生在connect成功时
    InetAddr server(serverport, serverip);
    if (connect(sockfd, server.Addr(), server.Length()) != 0)
    {
        LOG(LogLevel::ERROR) << "connect server error";
        exit(SOCKET_CONNECT_ERR);
    }
    std::cout << "connet " << server.ToString() << " success" << std::endl;

    while (true)
    {
        std::cout << "Please Enter@ ";
        std::string line;
        std::getline(std::cin, line); // 获取输入
        // 向服务端写数据
        ssize_t n = write(sockfd, line.c_str(), line.size());
        if (n > 0)
        {
            // 读取数据
            char buffer[1024];
            ssize_t m = read(sockfd, buffer, sizeof(buffer) - 1);
            if(m > 0)
            {
                buffer[m] = 0;
                std::cout << "server@ " << buffer << std::endl;
            }
        }
    }

    return 0;
}